package com.frikinet.lifeguard.gui;

import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.lobobrowser.html.UserAgentContext;
import org.lobobrowser.html.gui.HtmlPanel;
import org.lobobrowser.html.test.SimpleHtmlRendererContext;
import org.lobobrowser.html.test.SimpleUserAgentContext;
import org.w3c.dom.html2.HTMLElement;

import com.frikinet.lifeguard.services.LocalHttpServer;
import com.frikinet.lifeguard.util.VelocityUtil;

public class TemplateHtmlPanel extends HtmlPanel
{
	private static final long serialVersionUID = 1L;
	
	private static final String baseURI = String.format("http://localhost:%d", LocalHttpServer.serverPort);

	private UserAgentContext uaContext;
	
	private List<HtmlBehaviour> behaviours = new ArrayList<HtmlBehaviour>();
	
	public TemplateHtmlPanel()
	{
		super();
		
		uaContext = new TemplateUserAgentContext();
	}
	
	public TemplateHtmlPanel(HtmlBehaviour ...behaviours)
	{
		this();
		this.behaviours.addAll(Arrays.asList(behaviours));
	}
	
	public void addHtmlBehaviour(HtmlBehaviour behaviour)
	{
		behaviours.add(behaviour);
	}
	
	public void navigate(String template, Map<String, Object> context)
	{
		try
		{
			setHtml(VelocityUtil.getDocument(template, context), baseURI, new TemplateHtmlRenderer(this, uaContext));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public class TemplateUserAgentContext extends SimpleUserAgentContext
	{
		public TemplateUserAgentContext()
		{
			super();
			setExternalCSSEnabled(true);
			setScriptingEnabled(true);
		}
	}
	
	public class TemplateHtmlRenderer extends SimpleHtmlRendererContext
	{

		public TemplateHtmlRenderer(HtmlPanel contextComponent, UserAgentContext ucontext)
		{
			super(contextComponent, ucontext);
		}

		@Override
		public void linkClicked(HTMLElement linkNode, URL url, String target)
		{
			for(HtmlBehaviour behaviour: TemplateHtmlPanel.this.behaviours)
			{
				if(behaviour.checkElement(linkNode))
				{
					behaviour.performLinkClicked(this, linkNode, url, target);
				}
			}
		}

		@Override
		public boolean onContextMenu(HTMLElement element, MouseEvent event)
		{
			boolean handled = false;
			for(HtmlBehaviour behaviour: TemplateHtmlPanel.this.behaviours)
			{
				if(behaviour.checkElement(element))
				{
					handled = handled || behaviour.performContextMenu(this, element, event);
				}
			}
			return handled;
		}

	}
}
